package com.imooc.o2o.web.shopadmin;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.imooc.o2o.entity.Area;
import com.imooc.o2o.entity.ShopCategory;
import com.imooc.o2o.service.AreaService;
import com.imooc.o2o.util.CodeUtil;
import com.imooc.o2o.util.FileUtil;
import com.imooc.o2o.util.HttpServletRequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.o2o.dto.ShopExecution;
import com.imooc.o2o.entity.PersonInfo;
import com.imooc.o2o.entity.Shop;
import com.imooc.o2o.enums.ShopStateEnum;
//import com.imooc.o2o.service.LocalAuthService;
import com.imooc.o2o.service.ShopCategoryService;
import com.imooc.o2o.service.ShopService;
//import com.imooc.o2o.util.CodeUtil;
//import com.imooc.o2o.util.HttpServletRequestUtil;

@Controller
@RequestMapping("/shopadmin")
public class ShopManagementController {
	@Autowired
	private ShopService shopService;
	@Autowired
	private ShopCategoryService shopCategoryService;
	@Autowired
	private AreaService areaService;
//	@Autowired
//	private LocalAuthService localAuthService;

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ResponseBody
	private Map<String, Object> list(HttpServletRequest request) {
		//1.接收并转化相应的参数,包括店铺信息以及图片信息
		//定义返回值
		Map<String, Object> modelMap = new HashMap<String, Object>();
//		PersonInfo user = (PersonInfo) request.getSession()
//				.getAttribute("user");
//		long employeeId = user.getUserId();
//		if (hasAccountBind(request, employeeId)) {
//			modelMap.put("hasAccountBind", true);
//		} else {
//			modelMap.put("hasAccountBind", false);
//		}
		List<Shop> list = new ArrayList<Shop>();
		try {
			Shop shopCondition = new Shop();
			shopCondition.setOwnerId(8L);
//			ShopExecution shopExecution = shopService
//					.getByEmployeeId(employeeId);
			ShopExecution shopExecution = shopService
					.getShopList(shopCondition,0,100);
//			list = shopExecution.getShopList();
			modelMap.put("shopList", shopExecution.getShopList());
			//将用户信息返回前台
//			modelMap.put("user", user);
			modelMap.put("success", true);
			// 列出店铺成功之后，将店铺放入session中作为权限验证依据，即该帐号只能操作它自己的店铺
//			request.getSession().setAttribute("shopList", list);
		} catch (Exception e) {
			e.printStackTrace();
			modelMap.put("success", false);
			modelMap.put("errMsg", e.toString());
		}
		return modelMap;
	}
	/**
	 *
	 */
	@RequestMapping(value = "/getshopmanagementinfo",method = RequestMethod.GET)
	@ResponseBody
	private Map<String,Object> getShopManagementInfo(HttpServletRequest request){
		Map<String,Object> modelMap = new HashMap<String, Object>();
//		Long shopId = HttpServletRequestUtil.getLong(request,"shopId");
		Long shopId = HttpServletRequestUtil.getLong(request,"shopId");
		//如果参数里没有shopId
		if(shopId<=0){
			Object currentShopObj = request.getSession().getAttribute("currentShop");
			if (currentShopObj == null){
				modelMap.put("redirect",true);
				modelMap.put("url", "/shopadmin/list");
			}
			else {
				Shop currentShop = (Shop) currentShopObj;
				modelMap.put("redirect",false);
				modelMap.put("shopId", currentShop.getShopId());
			}
		}
		else {
			Shop currentShop = new Shop();
			currentShop.setShopId(shopId);
			request.getSession().setAttribute("currentShop", currentShop);
			modelMap.put("redirect", false);
		}
		return modelMap;
	}


	@RequestMapping(value = "/getshopbyid", method = RequestMethod.GET)
	@ResponseBody
	private Map<String, Object> getShopById(@RequestParam Long shopId,
			HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		if (shopId != null && shopId > -1) {
			Shop shopadmin = shopService.getByShopId(shopId);
			ShopCategory shopCategory = shopCategoryService.getShopCategoryById(shopadmin.getShopCategoryId());
			shopadmin.setShopCategory(shopCategory);
//			shopadmin.getShopCategory().setShopCategoryName(
//					shopCategoryService.getShopCategoryById(
//							shopadmin.getShopCategory().getShopCategoryId())
//							.getShopCategoryName());
//			shopadmin.getParentCategory().setShopCategoryName(
//					shopCategoryService.getShopCategoryById(
//							shopadmin.getParentCategory().getShopCategoryId())
//							.getShopCategoryName());
			modelMap.put("shopadmin", shopadmin);
			request.getSession().setAttribute("currentShop", shopadmin.getShopId());
			List<Area> areaList = new ArrayList<Area>();
//			try {
			areaList = areaService.getAreaList();
//			} catch (IOException e) {
//				modelMap.put("success", false);
//				modelMap.put("errMsg", e.toString());
//			}
			modelMap.put("areaList", areaList);
			modelMap.put("success", true);
		} else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "empty shopId");
		}
		return modelMap;
	}

	@RequestMapping(value = "/getshopinitinfo", method = RequestMethod.GET)
	@ResponseBody
	private Map<String, Object> getShopInitInfo() {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		List<ShopCategory> shopCategoryList = new ArrayList<ShopCategory>();
		List<Area> areaList = new ArrayList<Area>();
		try {
//			shopCategoryList = shopCategoryService
//					.getAllSecondLevelShopCategory();
			ShopCategory shopCategory = new ShopCategory();
			shopCategory.setParentId(10L);
			shopCategoryList = shopCategoryService
					.getShopCategoryList(shopCategory.getParentId());
			areaList = areaService.getAreaList();
		} catch (IOException e) {
			modelMap.put("success", false);
			modelMap.put("errMsg", e.toString());
		}
		modelMap.put("shopCategoryList", shopCategoryList);
		modelMap.put("areaList", areaList);
		modelMap.put("success", true);
		return modelMap;
	}

	@RequestMapping(value = "/modifyshop", method = RequestMethod.POST)
	@ResponseBody
	private Map<String, Object> modifyShop(HttpServletRequest request) {
		boolean statusChange = HttpServletRequestUtil.getBoolean(request,
				"statusChange");
		Map<String, Object> modelMap = new HashMap<String, Object>();
		if (!statusChange && !CodeUtil.checkVerifyCode(request)) {
			modelMap.put("success", false);
			modelMap.put("errMsg", "输入了错误的验证码");
			return modelMap;
		}
		ObjectMapper mapper = new ObjectMapper();
		Shop shopadmin = null;
		String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
		MultipartHttpServletRequest multipartRequest = null;
		CommonsMultipartFile shopImg = null;
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		//如果有上传的文件流
		if (multipartResolver.isMultipart(request)) {
			multipartRequest = (MultipartHttpServletRequest) request;
			shopImg = (CommonsMultipartFile) multipartRequest
					.getFile("shopImg");
		} else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "上传图片不能为空");
			return modelMap;
		}
		try {
			shopadmin = mapper.readValue(shopStr, Shop.class);
		} catch (Exception e) {
			modelMap.put("success", false);
			modelMap.put("errMsg", e.toString());
			return modelMap;
		}
		Long currentShopId = (Long) request.getSession().getAttribute("currentShop");
		shopadmin.setShopId(currentShopId);
		//2.修改店铺信息
		if (shopadmin != null && shopadmin.getShopId() != null) {
			filterAttribute(shopadmin);
			try {
				ShopExecution se = shopService.modifyShop(shopadmin, shopImg.getInputStream(), shopImg.getOriginalFilename());
//				if (se.getState() == ProductCategoryStateEnum.SUCCESS
				if (se.getState() == ShopStateEnum.SUCCESS
						.getState()) {
					modelMap.put("success", true);
				} else {
					modelMap.put("success", false);
					modelMap.put("errMsg", se.getStateInfo());
				}
			} catch (Exception e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", e.toString());
				return modelMap;
			}

		} else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "请输入店铺信息");
		}
		return modelMap;
	}

	@RequestMapping(value = "/registershop", method = RequestMethod.POST)
	@ResponseBody
	private Map<String, Object> registerShop(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		//1. 接收并转化相应的参数,包括店铺信息以及图片信息
		//获取前端传递过来的信息(包括文件流),并将其转换为实体类
		if (!CodeUtil.checkVerifyCode(request)) {
			modelMap.put("success", false);
			modelMap.put("errMsg", "输入了错误的验证码");
			return modelMap;
		}
		ObjectMapper mapper = new ObjectMapper();
		Shop shop = null;
		String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
		MultipartHttpServletRequest multipartRequest = null;
		CommonsMultipartFile shopImg = null;
		//从会话上下文中获取上传文件相关的内容
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		//如果有上传的文件流
		if (multipartResolver.isMultipart(request)) {
			multipartRequest = (MultipartHttpServletRequest) request;
			shopImg = (CommonsMultipartFile) multipartRequest
					.getFile("shopImg");
		} else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "上传图片不能为空");
			return modelMap;
		}
		//以上接收前端传递过来的信息,下面使用jackson json databind转换为shop实体类
		try {
			shop = mapper.readValue(shopStr, Shop.class);
		} catch (Exception e) {
			modelMap.put("success", false);
			modelMap.put("errMsg", e.toString());
//			modelMap.put("errMsg", "jackson json");
			return modelMap;
		}
		//2. 注册店铺
		if (shop != null && shopImg != null) {
			try {
				PersonInfo user = (PersonInfo) request.getSession()
						.getAttribute("user");
				PersonInfo owner = new PersonInfo();
//				shop.setOwnerId(user.getUserId());
				shop.setOwnerId(8L);
				File shopImgFile = new File(FileUtil.getImgBasePath() + FileUtil.getRandomFileName());
//				try {
//					shopImgFile.createNewFile();
//				} catch (IOException e) {
//					modelMap.put("success", false);
//					modelMap.put("errMsg", e.toString());
//					return modelMap;
//				}
//				try {
//					inputStreamToFile(shopImg.getInputStream(),shopImgFile);
//				} catch (IOException e) {
//					modelMap.put("success", false);
//					modelMap.put("errMsg", e.toString());
//					return modelMap;
//				}
				ShopExecution se = null;
				try {
					se = shopService.addShop(shop, shopImg.getInputStream(), shopImg.getOriginalFilename());
					if (se.getState() == ShopStateEnum.CHECK.getState()) {
						modelMap.put("success", true);
//						// 若shop创建成功，则加入session中，作为权限使用
						@SuppressWarnings("unchecked")
						//该用户可以操作的店铺列表
						List<Shop> shopList = (List<Shop>) request.getSession()
								.getAttribute("shopList");
						if (shopList != null && shopList.size() > 0) {
							shopList.add(se.getShop());
							request.getSession().setAttribute("shopList", shopList);
						} else {
							shopList = new ArrayList<Shop>();
							shopList.add(se.getShop());
							request.getSession().setAttribute("shopList", shopList);
						}
					} else {
						modelMap.put("success", false);
						modelMap.put("errMsg", se.getStateInfo());
					}
				} catch (IOException e) {
					modelMap.put("success", false);
//					modelMap.put("errMsg", e.getMessage());
					modelMap.put("errMsg", "IO exc");
					return modelMap;
				}
			} catch (RuntimeException e) {
				modelMap.put("success", false);
//				modelMap.put("errMsg", e.toString());
				modelMap.put("errMsg", "Run");
				return modelMap;
			}

		} else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "请输入店铺信息");
		}
		return modelMap;
	}

	private void filterAttribute(Shop shop) {

	}

//	private boolean hasAccountBind(HttpServletRequest request, long userId) {
//		if (request.getSession().getAttribute("bindAccount") == null) {
//			LocalAuth localAuth = localAuthService.getLocalAuthByUserId(userId);
//			if (localAuth != null && localAuth.getUserId() != null) {
//				request.getSession().setAttribute("bindAccount", localAuth);
//				return true;
//			} else {
//				return false;
//			}
//		} else {
//			return true;
//		}
//	}
//	private static void inputStreamToFile(InputStream ins , File file){
//		OutputStream os = null;
//		try{
//			os = new FileOutputStream(file);
//			int bytesRead = 0;
//			byte[] buffer = new byte[1024];
//			while ((bytesRead = ins.read(buffer)) != -1){
//				os.write(buffer, 0 ,bytesRead);
//			}
//		}catch (Exception e){
//			throw new RuntimeException("调用inputStreamToFile产生异常" + e.getMessage());
//		}finally {
//			try{
//				if (os != null){
//					os.close();
//				}
//				if(ins != null){
//					ins.close();
//				}
//			}catch (IOException e){
//				throw new RuntimeException("inputStreamToFile关闭io产生异常" + e.getMessage());
//			}
//		}
//	}
}
